package com.xpgk.mvc.deptStation;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.xpgk.annotation.Service;
import com.xpgk.constant.ConstantInit;
import com.xpgk.constant.ConstantRender;
import com.xpgk.dto.RenderBean;
import com.xpgk.dto.ZtreeNode;
import com.xpgk.mvc.base.BaseService;
import com.xpgk.mvc.dept.Department;
import com.xpgk.mvc.dept.DepartmentService;
import com.xpgk.mvc.organizationLevel.OrganLevelRight;
import com.xpgk.mvc.right.Right;
import com.xpgk.plugin.ParamInitPlugin;
import com.xpgk.tools.ToolCache;

@Service(name = DeptStationService.serviceName)
public class DeptStationService extends BaseService {

	@SuppressWarnings("unused")
	private static final Log log = Log.getLog(DepartmentService.class);

	public static final String serviceName = "deptStationService";
	
	/**
	 * 岗位树形图
	 * 
	 * @param cxt
	 * @param parentIds
	 * @return
	 */
	public List<ZtreeNode> childNodeData(String cxt, String parentIds, String curUserStationids) {
		List<DeptStation> list = null;
		if (null != parentIds) {
			String sql = getSqlMy(DeptStation.sqlId_childNode);
			list = DeptStation.dao.find(sql, parentIds);

		} else {
			list = new ArrayList<>();
			list.add(DeptStation.dao.findById(curUserStationids));
		}

		List<ZtreeNode> nodeList = new ArrayList<ZtreeNode>();
		ZtreeNode node = null;

		for (DeptStation station : list) {
			node = new ZtreeNode();
			node.setId(station.getPKValue());
			node.setName(station.getStr(DeptStation.column_name));
			node.setIsParent(station.getStr(DeptStation.column_isparent));
			node.setIcon(cxt + ConstantRender.icon_path + station.getStr(DeptStation.column_icon));
			nodeList.add(node);
		}

		return nodeList;
	}
	
	/**
	 * 添加岗位
	 * 
	 * @param pIds
	 * @param names
	 * @param orderIds
	 * @return
	 */
	public String addStation(String pIds, String name, int orderId, int level) {
		DeptStation pStation = DeptStation.dao.findById(pIds);
		pStation.set(DeptStation.column_isparent, "true").update();

		DeptStation station = new DeptStation();
		station.set(Department.column_parentids, pIds);
		station.set(Department.column_orderid, orderId);
		station.set(Department.column_name, name);
		station.set(Department.column_level, level + 1);
		station.save();

		return station.getPKValue();
	}
	
	/**
	 * 更改岗位名称
	 * 
	 * @param ids
	 * @param names
	 */
	public void updateStation(String ids, String name) {
		DeptStation station = DeptStation.dao.findById(ids);
		station.set(DeptStation.column_name, name).update();
	}
	
	/**
	 * 删除岗位
	 * 
	 * @param ids
	 * @return
	 */
	public String deleteStation(String ids) {
		DeptStation station = DeptStation.dao.findById(ids);

		// 是否存在子节点
		if (station.getStr(DeptStation.column_isparent).equals("true")) {
			return "存在子节点，不能直接删除"; // 存在子节点，不能直接删除
		}

		// 岗位下是否存在人
		String countSql = getSqlMy(DeptStation.sqlId_userCount);
		long count = Db.use(ConstantInit.db_dataSource_main).queryNumber(countSql, ids).longValue();
		if (count != 0) {
			return "岗位下存在人员，不能删除"; // 部门下存在人，不能删除
		}

		// 修改上级节点的isparent
		DeptStation pStation = DeptStation.dao.findById(station.getStr(DeptStation.column_parentids));
		String sql = getSqlMy(DeptStation.sqlId_childCount);
		Record record = Db.use(ConstantInit.db_dataSource_main).findFirst(sql, pStation.getPKValue());
		Long counts = record.getNumber("counts").longValue();
		if (counts == 1) {
			pStation.set(Department.column_isparent, "false");
			pStation.update();
		}

		// 删除
		DeptStation.dao.deleteById(ids);

		return ConstantRender.render_success;
	}
	
	/**
	 * 权限树形图
	 * 
	 * @param cxt
	 * @param parentIds
	 * @return
	 */
	public List<ZtreeNode> rightChildNodeData(String cxt, String parentIds, String stationIds, String curUserStationIds) {
		List<Right> list = null;
		if (null != parentIds) {
			String sql = getSqlMy(DeptStationRight.sqlId_childNode);
			list = Right.dao.find(sql, stationIds, parentIds, curUserStationIds, parentIds);

		} else {
			String sql = getSqlMy(DeptStationRight.sqlId_rootNode);
			list = Right.dao.find(sql, stationIds, curUserStationIds);
		}

		List<ZtreeNode> nodeList = new ArrayList<ZtreeNode>();
		ZtreeNode node = null;

		for (Right right : list) {
			node = new ZtreeNode();
			node.setId(right.getPKValue());
			node.setName(right.getStr(Right.column_name));
			node.setIsParent(right.getStr(Right.column_isparent));
			node.setChecked(right.getStr("checked"));
			node.setIcon(cxt + ConstantRender.icon_path + right.getStr(Right.column_icon));
			nodeList.add(node);
		}

		return nodeList;
	}
	
	/**
	 * 添加岗位权限
	 * 
	 * @param ids
	 * @param StationIds
	 * @param result
	 * @return
	 */
	public RenderBean addStationRight(String ids, String stationIds, String curUserStationIds, RenderBean result) {
		// 添加自己
		Right right = Right.dao.findById(ids);
		DeptStationRight dsr = new DeptStationRight();
		dsr.set(DeptStationRight.column_stationIds, stationIds).set(DeptStationRight.column_rightIds, ids).save();

		// 添加子节点
		addChildStationRight(ids, stationIds, curUserStationIds);

		// 添加父节点
		addParentStationRight(right.getStr(Right.column_parentids), stationIds);
		
		//添加岗位权限缓存
		cacheAdd(stationIds);

		result.setCode(ConstantRender.render_success_code);
		return result;
	}
	
	// 递归添加子节点
	public void addChildStationRight(String parentIds, String stationIds, String curUserStationIds) {
		String sql = getSqlMy(DeptStationRight.sqlId_childNodeByStation);
		List<Right> childs = Right.dao.find(sql, curUserStationIds, parentIds);
		if (childs.size() > 0) {
			for (Right child : childs) {
				DeptStationRight dsr = DeptStationRight.dao.findByIds(child.getPKValue(), stationIds);
				if (null == dsr) {
					new DeptStationRight().set(DeptStationRight.column_stationIds, stationIds)
							.set(DeptStationRight.column_rightIds, child.getPKValue()).save();
				}
				addChildStationRight(child.getPKValue(), stationIds, curUserStationIds);
			}
		}

	}
	
	// 递归添加父节点
	public void addParentStationRight(String ids, String stationIds) {
		if (null != ids) {
			Right right = Right.dao.findById(ids);
			if (null != right) {
				DeptStationRight dsr = DeptStationRight.dao.findByIds(ids, stationIds);
				if (null == dsr) {
					new DeptStationRight().set(DeptStationRight.column_stationIds, stationIds)
							.set(DeptStationRight.column_rightIds, right.getPKValue()).save();
					addParentStationRight(right.getStr(Right.column_parentids), stationIds);
				}
			}
		}
	}
	
	/**
	 * 删除岗位权限
	 * 
	 * @param ids
	 * @param levelIds
	 * @param result
	 * @return
	 */
	public RenderBean delStationRight(String ids, String stationIds, String curUserStationIds, RenderBean result) {
		// 删除自己
		Right right = Right.dao.findById(ids);
		DeptStationRight.dao.findByIds(ids, stationIds).delete();

		// 删除子节点
		delChildStationRight(ids, stationIds, curUserStationIds);

		// 删除父节点
		delParentStationRight(right.getStr(Right.column_parentids), stationIds);
		
		//跟新岗位权限缓存
		cacheAdd(stationIds);

		result.setCode(ConstantRender.render_success_code);
		return result;
	}
	
	// 递归删除子节点
	public void delChildStationRight(String parentIds, String stationIds, String curUserStationIds) {
		String sql = getSqlMy(DeptStationRight.sqlId_childNodeByStation);
		List<Right> childs = Right.dao.find(sql, curUserStationIds, parentIds);
		if (childs.size() > 0) {
			for (Right child : childs) {
				DeptStationRight dsr = DeptStationRight.dao.findByIds(child.getPKValue(), stationIds);
				if (null != dsr) {
					dsr.delete();
				}
				delChildStationRight(child.getPKValue(), stationIds, curUserStationIds);
			}
		}
	}
	
	// 递归删除父节点
	public void delParentStationRight(String ids, String stationIds) {
		if (null != ids) {
			Right right = Right.dao.findById(ids);
			if (null != right) {
				String sql = getSqlMy(DeptStationRight.sqlId_countChild);
				List<DeptStationRight> childs = DeptStationRight.dao.find(sql, ids, stationIds);
				if (null == childs || childs.size() == 0) {
					DeptStationRight.dao.findByIds(ids, stationIds).delete();
					delParentStationRight(right.getStr(Right.column_parentids), stationIds);
				}
			}
		}
	}
	
	/**
	 * 获取缓存 描述：岗位拥有的功能
	 *
	 * @param ids
	 * @return
	 */
	public static List<Right> cacheGet(String stationIds) {
		List<Right> olist = ToolCache.get(ParamInitPlugin.cacheStart_station_right + stationIds);
		if (olist == null) {
			String sql = getSqlMy(DeptStationRight.sqlId_findRightByStationIds);
			olist = Right.dao.find(sql, stationIds);
		}
		return olist;
	}
	
	/**
	 * 添加或者更新缓存 描述：岗位拥有的功能
	 */
	public static void cacheAdd(String stationIds) {
		String sql = getSqlMy(DeptStationRight.sqlId_findRightByStationIds);
		List<Right> olist = Right.dao.find(sql, stationIds);
		ToolCache.set(ParamInitPlugin.cacheStart_station_right + stationIds, olist);
	}

	/**
	 * 删除缓存 描述：岗位拥有的功能
	 */
	public static void cacheRemove(String stationIds) {
		ToolCache.remove(ParamInitPlugin.cacheStart_station_right + stationIds);
	}

}
